<template>
  <el-container>
    <el-header>
      <TopBar />
    </el-header>
    <el-main class="el-main">
      <div class="school-manage-container">
        <!-- 页面标题 -->
        <div class="page-header">
          <h1>{{ schoolName || '学校管理' }}</h1>
          <el-button type="primary" @click="goToMyU">返回学校主页</el-button>
        </div>

        <!-- 管理导航 -->
        <div class="manage-nav">
          <router-link
            :to="`/school/${schoolId}/manage/info`"
            custom
            v-slot="{ navigate, isActive }"
          >
            <div
              class="nav-item"
              :class="{ active: activeTab === 'info' }"
              @click="navigateTo('info')"
            >
              <i class="el-icon-info"></i>
              基本信息
            </div>
          </router-link>

          <router-link
            :to="`/school/${schoolId}/manage/clubs`"
            custom
            v-slot="{ navigate, isActive }"
          >
            <div
              class="nav-item"
              :class="{ active: activeTab === 'clubs' }"
              @click="navigateTo('clubs')"
            >
              <i class="el-icon-office-building"></i>
              社团管理
            </div>
          </router-link>

          <router-link
            :to="`/school/${schoolId}/manage/applications`"
            custom
            v-slot="{ navigate, isActive }"
          >
            <div
              class="nav-item"
              :class="{ active: activeTab === 'applications' }"
              @click="navigateTo('applications')"
            >
              <i class="el-icon-document"></i>
              社团申请
            </div>
          </router-link>

          <router-link
            :to="`/school/${schoolId}/manage/members`"
            custom
            v-slot="{ navigate, isActive }"
          >
            <div
              class="nav-item"
              :class="{ active: activeTab === 'members' }"
              @click="navigateTo('members')"
            >
              <i class="el-icon-user"></i>
              成员管理
            </div>
          </router-link>

          <router-link
            :to="`/school/${schoolId}/manage/posts`"
            custom
            v-slot="{ navigate, isActive }"
          >
            <div
              class="nav-item"
              :class="{ active: activeTab === 'posts' }"
              @click="navigateTo('posts')"
            >
              <i class="el-icon-s-comment"></i>
              帖子管理
            </div>
          </router-link>
        </div>

        <!-- 内容区域 -->
        <div class="manage-content">
          <SchoolInfoEdit v-if="activeTab === 'info'" :school-id="schoolId" @updated="fetchSchoolData" />
          <SchoolClubs v-else-if="activeTab === 'clubs'" :school-id="schoolId" />
          <SchoolApplications v-else-if="activeTab === 'applications'" :school-id="schoolId" />
          <SchoolMembers v-else-if="activeTab === 'members'" :school-id="schoolId" />
          <SchoolPosts v-else-if="activeTab === 'posts'" :school-id="schoolId" />
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import TopBar from '../../components/TopBar.vue'
import SchoolInfoEdit from './SchoolInfoEdit.vue'
import SchoolClubs from './SchoolClubs.vue'
import SchoolApplications from './SchoolApplications.vue'
import SchoolMembers from './SchoolMembers.vue'
import SchoolPosts from './SchoolPosts.vue'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const schoolId = ref(route.params.id)
const activeTab = ref('info')

// 学校信息
const schoolName = ref('')
const schoolLogo = ref('')
const schoolDescription = ref('')
const schoolClubsCount = ref(0)
const schoolUsersCount = ref(0)
const schoolPostsCount = ref(0)
const currentUser = ref(null)

// 导航到指定标签页
const navigateTo = (tab) => {
  activeTab.value = tab
  router.push(`/school/${schoolId.value}/manage/${tab}`)
}

// 返回学校主页
const goToMyU = () => {
  router.push('/myu')
}

// 获取学校数据
const fetchSchoolData = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }

    // 获取用户信息
    const userResponse = await axios.get('http://localhost:5000/users/me', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    currentUser.value = userResponse.data

    // 获取学校信息
    const schoolResponse = await axios.get(`http://localhost:5000/school/${schoolId.value}`)
    const schoolData = schoolResponse.data

    // 检查用户是否是学校管理员
    const isAdmin = schoolData.admin && (
      (Array.isArray(schoolData.admin) && schoolData.admin.includes(currentUser.value._id)) ||
      (!Array.isArray(schoolData.admin) && schoolData.admin === currentUser.value._id)
    )

    if (!isAdmin) {
      ElMessage.error('您没有权限管理此学校')
      router.push('/myu')
      return
    }

    // 更新学校数据
    schoolName.value = schoolData.name
    schoolLogo.value = schoolData.logo
    schoolDescription.value = schoolData.description
    schoolClubsCount.value = schoolData.clubs ? schoolData.clubs.length : 0
    schoolUsersCount.value = schoolData.users ? schoolData.users.length : 0

    // 获取学校帖子数量
    const postsResponse = await axios.get(`http://localhost:5000/schools/${schoolId.value}/posts`)
    schoolPostsCount.value = postsResponse.data ? postsResponse.data.length : 0

    // 从路由中获取当前标签页
    const pathParts = route.path.split('/')
    const lastPart = pathParts[pathParts.length - 1]
    if (lastPart && lastPart !== 'manage') {
      activeTab.value = lastPart
    }
  } catch (error) {
    console.error('获取学校数据失败:', error)
    ElMessage.error('获取学校数据失败')
  }
}

onMounted(async () => {
  await fetchSchoolData()
})
</script>

<style scoped>
.el-main {
  padding: 0;
  background-color: #121212;
}

.school-manage-container {
  padding: 20px;
  color: #ffffff;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
}

.manage-nav {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #333;
}

.nav-item {
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  color: #b0bec5;
  transition: background-color 0.3s, color 0.3s;
  display: flex;
  align-items: center;
  position: relative;
}

.nav-item:hover {
  background-color: #28232e;
  color: #ffffff;
}

.nav-item.active {
  background-color: #1f1b24;
  color: #00aeff;
  border-left: 3px solid #00aeff;
}

.nav-item i {
  font-size: 18px;
  margin-right: 8px;
}

.manage-content {
  background-color: #1f1b24;
  border-radius: 8px;
  padding: 20px;
  min-height: 70vh;
}
</style>
